import { http } from '../api/axios';
import { OutputFile } from '../contexts/types'

export interface TaskResponse {
  task_id: string;
}

export interface TaskEvent {
  type: 'status' | 'think' | 'tool' | 'act'  | 'log'| 'error' | 'complete';
  message: string;
  result?:string;
  status?: string;
  steps?: any[];
}


export const taskService = {
  // 创建新任务
  createTask: async (prompt: string): Promise<TaskResponse> => {
    return http.post<TaskResponse>('/execution/tasks', { prompt });
  },

  // 获取任务事件流
  getTaskEvents: (taskId: string, onEvent: (event: TaskEvent) => void) => {
    const eventSource = new EventSource(`http://localhost:5172/api/v1/execution/tasks/${taskId}/events`);

    eventSource.onmessage = (event) => {
      const data = JSON.parse(event.data);
      onEvent(data);
    };

    // 处理不同类型的事件
    ['status', 'think', 'tool', 'log', 'act', 'error', 'complete'].forEach(eventType => {
      eventSource.addEventListener(eventType, (event: MessageEvent) => {
        if(event.data){
          const data = JSON.parse(event.data);
          console.log(eventType)
          onEvent({ type: eventType as TaskEvent['type'], ...data });
        }
      });
    });

    // 错误处理
    eventSource.onerror = (error) => {
      // 检查 EventSource 的 readyState
      
      if (eventSource.readyState === EventSource.CLOSED) {
        // 连接已关闭
        eventSource.close();
        return;
      } else if (eventSource.readyState === EventSource.CONNECTING) {
        // 正在尝试重连
        console.log('EventSource is attempting to reconnect...');
        return;
      }
      
      // 其他错误情况
      console.error('EventSource failed:', error);
      eventSource.close();
      onEvent({ type: 'error', message: '任务事件流连接失败' });
    };

    return {
      close: () => eventSource.close()
    };
  },

  // 获取任务文件列表
  getTaskFiles: async (taskId: string): Promise<OutputFile[]> => {
    try {
      const response = await http.get(`/execution/${taskId}/files`,null, {
        retryTimes: 0,        // 失败后重试3次
        cancelDuplicated: true // 取消重复请求
      });
      return response.files || [];
    } catch (error: any) {
      if (error.code === 404) {
        return [];
      } else {
        throw error;
      }
    }
  },
  // 下载任务文件
  downloadTaskFile: async (taskId: string, fileName: string): Promise<void> => {
    try {
      const response = await http.post(
        `/execution/download/${taskId}`,
        { file_path: fileName },
        { responseType: 'blob' }
      );

      // 创建下载链接
      const url = window.URL.createObjectURL(new Blob([response]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', fileName);
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(url);
    } catch (error) {
      console.error('Failed to download file:', error);
      throw error;
    }
  }
}; 